/*
 * @lc app=leetcode.cn id=94 lang=cpp
 *
 * [94] 二叉树的中序遍历
 * 
 * 方法2：Morris 中序遍历
 * - predecessor 节点：线索二叉树的前序结点 -> 当前 p 节点向左走一步，然后一直向右走至无法走为止
 */

#include <vector>
#include <stack>

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

// @lc code=start
class Solution
{
public:
    std::vector<int> inorderTraversal(TreeNode *root)
    {
        std::vector<int> result;
        std::stack<TreeNode*> tree_stack;
        TreeNode *p = root;

        while (p != nullptr || !tree_stack.empty())
        {
            if (p != nullptr) // 一路向左
            {
                tree_stack.push(p);
                p = p->left;
            }
            else 
            {
                p = tree_stack.top();
                tree_stack.pop();

                result.push_back(p->val);

                p = p->right; // 右转
            }
        }

        return result;
    }
};
// @lc code=end
